#include <iostream>
#include <memory>
#include <vector>
#include <string>
#include <fstream>
#include "Usage.hpp"
#include "Util.hpp"
#include "HttpServer.hpp"

#define ROOT "./wwwroot"
#define HOMEPAGE "/index.html"

void HandlerHttpRequst(int sock)
{
    char buffer[10240];
    ssize_t sz = recv(sock, buffer, sizeof(buffer) - 1, 0);
    if (sz > 0)
    {
        buffer[sz] = 0;
        std::cout << buffer << "==================\n" << std::endl;
    }

    // 获取目录消息
    std::vector<std::string> vline;
    Util::CutString(buffer, "\r\n", vline);

    std::vector<std::string> vblock;
    Util::CutString(vline[0], " ", vblock);

    // 设置web根目录
    // std::string file = vblock[1];
    std::string target = ROOT;
    if (vblock[1] == "/")
        target += HOMEPAGE;
    else
        target += vblock[1];

    std::cout << target << std::endl;
    // 打开文件分析
    std::string connect;
    std::ifstream in(target);
    if (in.is_open())
    {

        std::string line;
        while (std::getline(in, line))
        {
            connect += line;
        }
        in.close();
    }
    // 填充协议内容
    std::string HttpResponse;
    if (connect.empty())
    {
        HttpResponse = "HTTP/1.1 302 Found\r\n";
        // HttpResponse += "Content-Type: text/html,image/jpg\r\n";                           // Content-Type:数据类型
        HttpResponse += "location: http://121.37.153.162:8080/notexit.html\r\n"; // location：跳转的下一个网站
    }
    else
    {
        HttpResponse = "HTTP/1.1 200 OK\r\n";
        HttpResponse += ("Content-Length: " + std::to_string(connect.size()) + "\r\n");
        HttpResponse += "Set-Cookie: 这是一个Cookie\r\n";
    }
    HttpResponse += "\r\n";
    HttpResponse += connect;
    std::cout << HttpResponse << std::endl;
    send(sock, HttpResponse.c_str(), HttpResponse.size(), 0);

    // for(auto& it : vline)
    // {
    //     std::cout << it << "------"<< std::endl;
    // }
}

// ./HttpServer port
int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[1]);
        exit(1);
    }

    std::unique_ptr<HttpServer> server(new HttpServer(atoi(argv[1]), HandlerHttpRequst));
    server->start();

    return 0;
}